<?php
require '../config.php';

header('Content-Type: application/json');

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('请求失败');
    }

    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input || !isset($input['api_key']) || $input['api_key'] !== API_KEY || empty($input['kami'])) {
        throw new Exception('无效请求');
    }

    // 查询卡密（不过滤 status）
    $stmt = $pdo->prepare("SELECT * FROM kami WHERE kami_key = ?");
    $stmt->execute([$input['kami']]);
    $kami = $stmt->fetch();

    // 判断卡密是否存在
    if (!$kami) {
        throw new Exception('卡密不存在');
    }

    // 判断状态
if ((int)$kami['status'] === 0) {
    throw new Exception('该卡密已被禁用');
}

// 判断过期（只用first_use_time+时长，不用expire_time）
if ($kami['first_use_time']) {
    $expire_time = null;
    switch ($kami['type']) {
        case '分钟卡': $expire_time = strtotime($kami['first_use_time']) + 60; break;
        case '小时卡': $expire_time = strtotime($kami['first_use_time']) + 3600; break;
        case '天卡': $expire_time = strtotime($kami['first_use_time']) + 86400; break;
        case '周卡': $expire_time = strtotime($kami['first_use_time']) + 604800; break;
        case '月卡': $expire_time = strtotime($kami['first_use_time']) + 2592000; break;
        case '季卡': $expire_time = strtotime($kami['first_use_time']) + 7776000; break;
        case '年卡': $expire_time = strtotime($kami['first_use_time']) + 31536000; break;
        case '永久卡': $expire_time = null; break;
    }
    if ($expire_time && $expire_time < time()) {
        throw new Exception('卡密已过期');
    }
}

    // 使用逻辑
    $pdo->beginTransaction();

if ($kami['use_count'] == 0) {
    // 首次使用，写入 first_use_time
    $update = $pdo->prepare("UPDATE kami SET use_count = use_count + 1, first_use_time = NOW() WHERE id = ?");
    $update->execute([$kami['id']]);
} else {
    // 非首次使用，只增加 use_count
    $update = $pdo->prepare("UPDATE kami SET use_count = use_count + 1 WHERE id = ?");
    $update->execute([$kami['id']]);
}

if ($kami['max_uses'] > 0 && ($kami['use_count'] + 1) >= $kami['max_uses']) {
    $disable = $pdo->prepare("UPDATE kami SET status = 0 WHERE id = ?");
    $disable->execute([$kami['id']]);
}

$pdo->commit();

    echo json_encode(['status' => 1, 'msg' => '验证成功']);

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['status' => 0, 'msg' => $e->getMessage()]);
}